package com.sist.ocs.config;

import com.sist.ocs.mqcallback.MsgSendConfirmCallBack;
import com.sist.ocs.mqcallback.MsgSendReturnCallback;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName RabbitMqConfig
 * @Description TODO
 * @Author: xmk
 * @Date: 2018/10/25 10:08
 * @Version: 1.0
 */
@Configuration
public class RabbitMqConfig {

    public static final String EXCHANGE = "myExchange";
    public static final String ROUTING_KEY1 = "queue_one_key1";
    public static final String ROUTING_KEY2 = "queue_one_key2";

    @Autowired
    private QueueConfig queueConfig;
    @Autowired
    private ExchangeConfig exchangeConfig;

    @Autowired
    private ConnectionFactory connectionFactory;

//    @Bean
//    public Binding binding_one(@Qualifier("firstQueue") Queue queue, DirectExchange directExchange) {
//        return BindingBuilder.bind(queue).to(directExchange).with(RabbitMqConfig.ROUTING_KEY1);
//    }

    @Bean
    public Binding binding_two(@Qualifier("secondQueue") Queue queue, DirectExchange directExchange) {
        return BindingBuilder.bind(queue).to(directExchange).with(RabbitMqConfig.ROUTING_KEY2);
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        /**若使用confirm-callback或return-callback，
         * 必须要配置publisherConfirms或publisherReturns为true
         * 每个rabbitTemplate只能有一个confirm-callback和return-callback
         */
        rabbitTemplate.setConfirmCallback(msgSendConfirmCallBack());
        rabbitTemplate.setReturnCallback(msgSendReturnCallback());
        /**
         * 使用return-callback时必须设置mandatory为true，或者在配置中设置mandatory-expression的值为true，
         * 可针对每次请求的消息去确定’mandatory’的boolean值，
         * 只能在提供’return -callback’时使用，与mandatory互斥
         */
        rabbitTemplate.setMandatory(true);

        return rabbitTemplate;
    }

    @Bean
    public MsgSendConfirmCallBack msgSendConfirmCallBack() {
        return new MsgSendConfirmCallBack();
    }

    @Bean
    public MsgSendReturnCallback msgSendReturnCallback() {
        return new MsgSendReturnCallback();
    }
}
